const Promise = require('bluebird');
const jobs = require('../../jobs/index');
const Notification = require('../models/notification');

module.exports = function(nt) {
    return Promise.try(() => {
        const time = nt.get('time');
        const status = nt.get('status');

        if(!time || time.getTime() < Date.now()) {
            throw new Error('推送时间不能小于当前时间');
        }

        if(status !== Notification.PENDING) {
            throw new Error('创建推送任务失败，状态错误');
        }

        return time;
    })
    .then(time => {
        return jobs.add('app-push', {
            title: `APP Push, notification_id=${nt.id}`,
            notification_id: nt.id
        }, {
            attempts: 3,
            delay: time
        });
    });
};